<script>
export default {
  name: "CommonList",
  components: {},
  props: {
    dataSource: {
      type: Array,
      default: () => [],
    },
    listOptions: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      columnsOptions: {
        KeyName: "id", // 行关键字
        columns: [],
        defaultChecked: [], // 默认选中的值
        bordered: true, // 是否需要边框
        isNeedIndex: true, // 是否需要序号， 默认要
        isNeedSelection: true, // 是否需要多选，默认要
        isNeedPageSize: true, // 是否需要分页， 默认要
        isNeedOperation: true, // 是否需要操作区
        isFixedColumns: false, // 是否固定条数
        pageSize: {
          current: 1,
          defaultPageSize: 10,
          total: 0,
          showTotal: (total) => `共 ${total} 条`,
        },
        selectedRow: [],
      },
    };
  },
  computed: {
    columns() {
      let columns = [];
      if (this.columnsOptions.isNeedIndex) {
        columns.push({
          title: "序号",
          dataIndex: "sequence_index_number",
          width: "80px",
          align: "center",
          customRender: (text, record, index) => {
            return index + 1;
          },
        });
      }
      columns = columns.concat(
        this.columnsOptions.columns.map((item) => {
          return {
            ...item,
            align: item.align || "center",
          };
        })
      );
      if (this.columnsOptions.isNeedOperation) {
        const Obj = {
          title: "操作区",
          key: "operation",
          align: "center",
          scopedSlots: { customRender: "operation" },
        };
        if (this.columnsOptions.operWidth) {
          Object.assign(Obj, {
            width: this.columnsOptions.operWidth,
          });
        }
        if (this.columnsOptions.isfixed) {
          Object.assign(Obj, {
            fixed: this.columnsOptions.isfixed,
          });
        }
        columns.push(Obj);
      }
      return columns;
    },
    rowSelection() {
      return {
        onSelect: (record, selected) => {
          selected
            ? this.selectedRow.push(record)
            : this.selectedRow.splice(
                this.selectedRow.findIndex(
                  (x) =>
                    x[this.columnsOptions.KeyName] ===
                    record[this.columnsOptions.KeyName]
                ),
                1
              );
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
          this.selectedRow = selected
            ? this.selectedRow.concat(changeRows)
            : this.selectedRow.filter(
                (x) =>
                  !changeRows.find(
                    (i) =>
                      i[this.columnsOptions.KeyName] ===
                      x[this.columnsOptions.KeyName]
                  )
              );
        },
        onChange: (selectedRowKeys, selectedRows) => {
          this.$emit("pageSelectedRow", this.selectedRow);
          this.$emit("selectedRowKeys", selectedRowKeys, selectedRows);
        },
        type: "checkbox",
        getCheckboxProps: (record) => {
          Object.assign(this.columnsOptions, this.listOptions);
          return {
            props: {
              defaultChecked: this.columnsOptions.defaultChecked.includes(
                this.getKeyName(record, this.columnsOptions.KeyName)
              ),
              disabled: this.columnsOptions.isFixedColumns
                ? this._isShowSelect(record, this.columnsOptions.KeyName) &&
                  this.columnsOptions.defaultChecked.includes(
                    this.getKeyName(record, this.columnsOptions.KeyName)
                  )
                : this.columnsOptions.defaultChecked.includes(
                    this.getKeyName(record, this.columnsOptions.KeyName)
                  ),
            },
          };
        },
      };
    },
    pageSize() {
      const page = {
        current: 1,
        defaultPageSize: 10,
        total: 0,
        showTotal: (total) => `共 ${total} 条`,
      };
      Object.assign(page, this.listOptions.pageSize);
      return page;
    },
  },
  mounted() {
    this.selectedRow = [];
    Object.assign(this.columnsOptions, this.listOptions);
  },
  methods: {
    _isShowSelect(record, keyName) {
      const key = this.getKeyName(record, keyName);
      return key && key.indexOf("FIX#####") !== -1;
    },
    getKeyName(record, keyname) {
      if (keyname && keyname.indexOf(".") !== -1) {
        const arr = keyname.split(".");
        return record[arr[0]][arr[1]];
      } else {
        return record[keyname];
      }
    },
  },
  // 渲染函数
  /**
     createElement的参数：
   1、一个 HTML 标签名、组件选项对象，或者resolve 了上述任何一种的一个 async 函数。必填项
        {String | Object | Function},  例：   'div'
   2、一个与模板中 attribute 对应的数据对象。可选。
        {Object}
   3、子级虚拟节点 (VNodes)，由 `createElement()` 构建而成，也可以使用字符串来生成“文本虚拟节点”。可选。
        {String | Array}  例：[
                               '先写一些文字',
                               createElement('h1', '一则头条'),
                               createElement(MyComponent, {
                                  props: {
                                    someProp: 'foobar'
                                  }
                                })
                               ]
   */
  render(createElement) {
    return createElement("a-table", {
      attrs: {
        ...this.$attrs,
        columns: this.columns,
        dataSource: this.dataSource,
        rowKey: (record) =>
          this.getKeyName(record, this.columnsOptions.KeyName),
        bordered: this.columnsOptions.bordered,
        pagination: this.columnsOptions.isNeedPageSize ? this.pageSize : false,
        rowSelection: this.columnsOptions.isNeedSelection
          ? this.rowSelection
          : null,
      },
      scopedSlots: this.$scopedSlots,
        /** v-on事件 */
      on: {
        ...this.$listeners,
        change: (current, filters, sorter, { currentDataSource }) => {
          this.$emit("pageChange", current, filters, sorter, {
            currentDataSource,
          });
        },
      },
    });
  },
};
</script>

<style scoped></style>
